package com.lich.factory;

import com.lich.CommonUtils;
import com.lich.Field;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class PostgresqlFieldFactory implements FieldFactory {
    @Override
    public List<Field> getFieldByTableName(Connection con, String tableName) throws Exception {
        if (CommonUtils.isEmptyString(tableName)) {
            throw new Exception("表名不能为空");
        }
        List<Field> fieldList = new ArrayList<>();
        try {
            //查询表的属性
            Statement stmt = con.createStatement();
            String sql = "select a.attname as field, t.typname as type, a.attnotnull as notnull, b.description as comment from pg_class c, pg_attribute a left outer join pg_description b" +
                    " on a.attrelid = b.objoid and a.attnum = b.objsubid, pg_type t where c.relname = '" + tableName + "' and a.attnum > 0 and a.attrelid = c.oid and a.atttypid = t.oid order by a.attnum";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                Field field = new Field();
                field.setName(rs.getString("field"));
                field.setType(rs.getString("type"));
                field.setNotnull(rs.getBoolean("notnull"));
                field.setComment(rs.getString("comment"));
                fieldList.add(field);
            }
            //查询主键信息
            sql = "select pg_constraint.conname as pk_name,pg_attribute.attname as colname,pg_type.typname as typename from pg_constraint inner join pg_class on pg_constraint.conrelid = pg_class.oid inner join pg_attribute on" +
                    " pg_attribute.attrelid = pg_class.oid and pg_attribute.attnum = pg_constraint.conkey[1] inner join pg_type on pg_type.oid = pg_attribute.atttypid where pg_class.relname = '" + tableName + "' and pg_constraint.contype='p'";
            rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String pk = rs.getString("colname");
                for (Field field : fieldList) {
                    if (CommonUtils.isEmptyString(pk)) {
                        break;
                    } else if (pk.equals(field.getName())) {
                        field.setPrimaryKey(true);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            con.close();
        }
        return fieldList;
    }
}
